package generic.net;

import java.beans.XMLEncoder;
import java.io.IOException;
import java.io.OutputStream;

/*
 * Allows Messages to be passed back and forth over a stream.
 *
 * Unlike the normal XMLEncoder, the MessageInputStream can pass multiple
 * messages in both directions.
 *
 * @see MessageInputStream
 * @author Adam Scarr <scarr.adam@gmail.com>
 */

public class MessageOutputStream {
    private OutputStream out;

    /**
     * Creates a new MessageOutputStream wrapping the given OutputStream
     * @param out The OutputStream to send messages over.
     */
    public MessageOutputStream(final OutputStream out) {
        this.out = out;
    }

    /**
     * Writes the given message.
     * @param message   The message to write.
     */
    public void write(Message message) throws IOException {
        XMLEncoder xmle = new XMLEncoder(new SubOutputStream(out));
        xmle.writeObject(message);
        xmle.close();
    }
}
